    //
//  PDFViewController.m
//  Digital Seamonsters
//
//  Created by Adam Cue on 1/29/11.
//  Copyright Adam Cue 2011.
//
//  This program is licensed and distributed under the terms of the GNU General Public License.  
//	The text for the license can be found in the license.txt file in this project.
//

#import "PDFViewController.h"
#import "DrawingInfo.h"

#define NOTE_OFFSET                     5
#define NOTE_CONTENT_HEIGHT           339
#define PEN_WIDTH_CONTENT_HEIGHT       77
#define COLOR_POPOVER_CONTENT_WIDTH   247
#define COLOR_POPOVER_CONTENT_HEIGHT  296
#define TOOLBAR_WIDTH                 230
#define TOOLBAR_HEIGHT                 44

static dispatch_queue_t readingQueue;

@interface PDFViewController (Private)
#pragma mark SetupMethods
- (void)setupToolbar;
- (void)setupAnnotationViews;
- (void)setupNotes;
- (void)setupPopovers;
- (void)setupHelpView;

#pragma mark HelperMethods
- (void)cacheReading;
- (NSArray *)readingFetchResults:(BOOL)isRecent;
- (NSURLRequest *)getLesson;
- (void)addDrawViews;
- (void)saveReading:(NSNumber *)recent;
- (void)animateInTutorialView;

#pragma mark UserActions
- (void)dismissTutorial;
@end

@implementation PDFViewController

@synthesize helpView = _helpView;
@synthesize fileURL = _fileURL;
@synthesize pdfScrollView = _pdfScrollView;
@synthesize annotationViews = _annotationViews;
@synthesize colorPopover = _colorPopover;
@synthesize notePopover = _notePopover;
@synthesize navigationPopover = _navigationPopover;
@synthesize listOfNotesPopover = _listOfNotesPopover;
@synthesize penWidthPopover = _penWidthPopover;
@synthesize pagePicker = _pagePicker;
@synthesize readingID;
@synthesize pdfName = _pdfName;
@synthesize thumbnail = _thumbnail;
@synthesize dataReading = _dataReading;
@synthesize annotationTouchPoints = _annotationTouchPoints;

//Initialize with the URL of the reading, the name, and the thumbnail.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil fileURL:(NSString *)selectedFileURL name:(NSString *)selectedName thumb:(UIImage *)selectedThumb{
   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
   if (self) {
      if(!readingQueue) readingQueue = dispatch_queue_create("com.cachalot.Reading", NULL);
      _annotationViews = [[NSMutableArray alloc] initWithCapacity:1];
      self.tabBarItem = [[[UITabBarItem alloc] initWithTitle:@"Readings" image:[UIImage imageNamed:@"reading"] tag:1] autorelease];
      self.fileURL = selectedFileURL;
      self.pdfName = selectedName;
      self.thumbnail = selectedThumb;
   }
   return self;
}

//Initialize with a reading loaded from CoreData.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil savedReading:(Reading *)selectedReading{
   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
   if (self) {
      if(!readingQueue) readingQueue = dispatch_queue_create("com.cachalot.Reading", NULL);
      _annotationViews = [[NSMutableArray alloc] initWithCapacity:1];
      self.tabBarItem = [[[UITabBarItem alloc] initWithTitle:@"Readings" image:[UIImage imageNamed:@"reading"] tag:1] autorelease];
      self.dataReading = selectedReading;
   }
   return self;
}

//Set up the buttons on the navigation bar, present the loading reading screen, and tell the UIWebView to load the reading.
- (void)viewDidLoad {
    [super viewDidLoad];
	// create a toolbar where we can place some buttons
	[self setupToolbar];
	self.pdfScrollView = [[_pdfView subviews] objectAtIndex:0];
	self.pdfScrollView.delegate = self;
	_pdfView.scalesPageToFit = YES;
	_pdfView.delegate = self;
	[DSBezelActivityView newActivityViewForView:self.view withLabel:@"Loading Reading..." width:160];        
	dispatch_async(readingQueue, ^{[_pdfView loadRequest:[self getLesson]];});
}

- (void)viewWillAppear:(BOOL)animated{
   [super viewWillAppear:animated];
   if(_listOfNotesPopover != nil){
      if(!_helpView && ![[NSUserDefaults standardUserDefaults] valueForKey:CACHALOT_READING_TUTORIAL_KEY]){
         [self setupHelpView];
         [self animateInTutorialView];
      }
   }
}

//Save CoreData context when the view is gone.
- (void)viewWillDisappear:(BOOL)animated{
   [super viewWillDisappear:animated];
	NSError *error;
	[[[MarineFetcher sharedInstance] managedObjectContext] save:&error];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
   // Overriden to allow any orientation.
   return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

- (void)dealloc {
   self.helpView = nil;
   self.fileURL = nil;
   self.pdfScrollView = nil;
   self.annotationViews = nil;
   self.colorPopover = nil;
   self.notePopover = nil;
   self.navigationPopover = nil;
   self.listOfNotesPopover = nil;
   self.penWidthPopover = nil;
   self.pagePicker = nil;
   self.pdfName = nil;
   self.thumbnail = nil;
   self.dataReading = nil;
   self.annotationTouchPoints = nil;
   [super dealloc];
}

#pragma mark SetupMethods
- (void)setupToolbar {
   UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, TOOLBAR_WIDTH, TOOLBAR_HEIGHT)];
	[toolbar setBarStyle: UIBarStyleBlackOpaque];
	NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];
	UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithTitle:@"Save Reading" style:UIBarButtonItemStyleBordered target:self action:@selector(save)];
	[buttons addObject:saveButton];
	[saveButton release];
	UIBarButtonItem *notesButton = [[UIBarButtonItem alloc] initWithTitle:@"Notes" style:UIBarButtonItemStyleBordered target:self action:@selector(notesClicked:)];
	[buttons addObject:notesButton];
	[notesButton release];
	UIBarButtonItem *navigateButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(navigate:)];
	navigateButton.style = UIBarButtonItemStyleBordered;
	[buttons addObject:navigateButton];
	[navigateButton release];
	[toolbar setItems:buttons animated:NO];
	[buttons release];
	UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:toolbar];
	[toolbar release];
	[self.navigationItem setRightBarButtonItem:rightBarButton];
	[rightBarButton release];
}

- (void)setupAnnotationViews {
   heightOfPage = self.pdfScrollView.contentSize.height / numberOfPages;
	int i = 0;
	int pageNums = numberOfPages;
	_annotationTouchPoints = [[NSMutableArray alloc] initWithCapacity:numberOfPages];
	int e = 0;
	for(e = 0; e < numberOfPages; e++){
		[self.annotationTouchPoints addObject:[NSArray array]];
	}
   while(pageNums > 0){
		AnnotationView *annotationView = [[AnnotationView alloc] initWithFrame:CGRectMake(self.pdfScrollView.frame.origin.x, self.pdfScrollView.frame.origin.y + i * heightOfPage, self.pdfScrollView.contentSize.width, heightOfPage)];
		annotationView.delegate = self;
		annotationView.page = i;
		annotationView.tag = i == 0 ? -1 : i;
		if(i == 0 || i == 1){
			[self.pdfScrollView addSubview:annotationView];
			[self.pdfScrollView bringSubviewToFront:annotationView];
		}
		[self.annotationViews addObject:annotationView];
		i++;
		pageNums--;
	}
   NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
	NSString *fileDrawing = [NSString stringWithFormat:@"reading%d", readingID];
	path = [path stringByAppendingPathComponent:fileDrawing];
	NSArray *results = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
	int index = 0;
	for(NSMutableArray *touchPoints in results){
		for(DrawingInfo *point in touchPoints){
			[[[self.annotationViews objectAtIndex:index] touchPoints] addObject:point];
		}
		[self.annotationTouchPoints replaceObjectAtIndex:index withObject:[[self.annotationViews objectAtIndex:index] touchPoints]];
		index++;
	}
}

- (void)setupNotes {
   NSFetchRequest *noteRequest = [[NSFetchRequest alloc] init];
	NSEntityDescription *noteEntity = [NSEntityDescription entityForName:@"Note" inManagedObjectContext:[[MarineFetcher sharedInstance] managedObjectContext]];
	[noteRequest setEntity:noteEntity];
	[noteRequest setPredicate:[NSPredicate predicateWithFormat:@"readingID == %@", [NSNumber numberWithInt:readingID]]];
	NSError *noteError;
	NSArray *noteFetchResults = [[[MarineFetcher sharedInstance] managedObjectContext] executeFetchRequest:noteRequest error:&noteError];
	if (noteFetchResults == nil) {
		NSLog(@"%@", noteError);
	}
	for(Note *note in noteFetchResults){
		NoteTabButton *noteTabButton = [[[NSBundle mainBundle] loadNibNamed:@"NoteTabButton" owner:nil options:nil] objectAtIndex:0];
		noteTabButton.delegate = self;
		noteTabButton.frame = CGRectMake(NOTE_OFFSET, [note.y intValue], noteTabButton.frame.size.width, noteTabButton.frame.size.height);
		noteTabButton.noteLabel.text = note.text;
		noteTabButton.note = note;
		[self.pdfScrollView addSubview:noteTabButton];
		[self.pdfScrollView bringSubviewToFront:noteTabButton];
	}
}

- (void)setupPopovers {
   ColorPickerViewController *colorPicker = [[ColorPickerViewController alloc] initWithNibName:@"ColorPickerViewController" bundle:[NSBundle mainBundle] annotationViews:self.annotationViews];
	_colorPopover = [[UIPopoverController alloc] initWithContentViewController:colorPicker];
	colorPicker.colorPopover = self.colorPopover;
	[self.colorPopover setPopoverContentSize:CGSizeMake(COLOR_POPOVER_CONTENT_WIDTH, COLOR_POPOVER_CONTENT_HEIGHT)];
	[colorPicker release];
	PenWidthViewController *penWidth = [[PenWidthViewController alloc] initWithNibName:@"PenWidthViewController" bundle:[NSBundle mainBundle] annotationViews:self.annotationViews];
	_penWidthPopover = [[UIPopoverController alloc] initWithContentViewController:penWidth];
	penWidth.penWidthPopover = self.penWidthPopover;
	[self.penWidthPopover setPopoverContentSize:CGSizeMake(320, PEN_WIDTH_CONTENT_HEIGHT)];
	[penWidth release];
	NotesTableViewController *notesTable = [[NotesTableViewController alloc] init];
	notesTable.readingID = readingID;
	notesTable.dimensionOfPage = heightOfPage;
	notesTable.delegate = self;
	_listOfNotesPopover = [[UIPopoverController alloc] initWithContentViewController:notesTable];
	[self.listOfNotesPopover setPopoverContentSize:CGSizeMake(320, 480)];
	[notesTable release];
}

- (void)setupHelpView {
   if(![[NSUserDefaults standardUserDefaults] valueForKey:CACHALOT_READING_TUTORIAL_KEY]){
      _helpView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 1024.0, 704.0)];
      self.helpView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.66];
      UIImageView * readingsHelpView = [[[UIImageView alloc] initWithFrame:CGRectMake(37.0, 69.0, 266.0, 171.0)] autorelease];
      readingsHelpView.image = [UIImage imageNamed:@"readings-help"];
      readingsHelpView.userInteractionEnabled = NO;
      [self.helpView addSubview:readingsHelpView];
      UIImageView * saveNotesPdfHelpView = [[[UIImageView alloc] initWithFrame:CGRectMake(629.0, 0.0, 319.0, 186.0)] autorelease];
      saveNotesPdfHelpView.image = [UIImage imageNamed:@"save-notes-pdf-help"];
      saveNotesPdfHelpView.userInteractionEnabled = NO;
      [self.helpView addSubview:saveNotesPdfHelpView];
      UIImageView * annotationToolsHelpView = [[[UIImageView alloc] initWithFrame:CGRectMake(629.0, 385.0, 317.0, 263.0)] autorelease];
      annotationToolsHelpView.image = [UIImage imageNamed:@"annotation-tools-help"];
      annotationToolsHelpView.userInteractionEnabled = NO;
      [self.helpView addSubview:annotationToolsHelpView];
      UITapGestureRecognizer * hideTutorialTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissTutorial)];
      [self.helpView addGestureRecognizer:hideTutorialTap];
      [hideTutorialTap release];
      UILabel * tutorialLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
      tutorialLabel.text = @"Tap anywhere to dismiss tutorial";
      tutorialLabel.textColor = [UIColor whiteColor];
      tutorialLabel.backgroundColor = [UIColor clearColor];
      tutorialLabel.font = [UIFont fontWithName:@"MarkerFelt-Thin" size:44.0];
      [tutorialLabel sizeToFit];
      tutorialLabel.center = self.helpView.center;
      [self.helpView addSubview:tutorialLabel];
      self.helpView.alpha = 0.0;
   }
}

#pragma mark HelperMethods
- (void)cacheReading {
   if(_dataReading == nil){
		NSArray *readingFetchResults = [self readingFetchResults:YES];
		for(Reading *reading in readingFetchResults){
			[[[MarineFetcher sharedInstance] managedObjectContext] deleteObject:reading];
		}
	}
	[self saveReading:[NSNumber numberWithBool:YES]];
}

- (NSArray *)readingFetchResults:(BOOL)isRecent {
   NSFetchRequest *readingRequest = [[NSFetchRequest alloc] init];
   NSEntityDescription *readingEntity = [NSEntityDescription entityForName:@"Reading" inManagedObjectContext:[[MarineFetcher sharedInstance] managedObjectContext]];
   [readingRequest setEntity:readingEntity];
   [readingRequest setPredicate:[NSPredicate predicateWithFormat:@"isRecent == %@", [NSNumber numberWithBool:isRecent]]];
   NSError *readingError;
   NSArray *readingFetchResults = [[[MarineFetcher sharedInstance] managedObjectContext] executeFetchRequest:readingRequest error:&readingError];
   if (readingFetchResults == nil) {
      NSLog(@"%@", readingError);
   }
   return readingFetchResults;
}

- (NSURLRequest *)getLesson {
	NSURL *pdfURL;
	NSURLRequest *request;
	BOOL foundRecent = NO;
	NSArray *readingFetchResults = [self readingFetchResults:YES];
	for(Reading *reading in readingFetchResults){
		if([self.pdfName isEqualToString:reading.name]){
			foundRecent = YES;
			pdfURL = [NSURL fileURLWithPath:reading.path];
			request = [NSURLRequest requestWithURL:pdfURL];
		}
	}
	if(foundRecent == NO && self.fileURL != nil){
		pdfURL = [NSURL URLWithString:self.fileURL];
		request = [NSURLRequest requestWithURL:pdfURL];
	}
	else if(foundRecent == NO){
		pdfURL = [NSURL fileURLWithPath:self.dataReading.path];
		request = [NSURLRequest requestWithURL:pdfURL];
	}
	NSData *data = [NSData dataWithContentsOfURL:pdfURL];
	CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((CFDataRef)data);
	CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(dataProvider);
	CGDataProviderRelease(dataProvider);
	_pagePicker = [[PDFPagePickerGridViewController alloc] initWithNibName:nil bundle:nil document:document
                                                          annotationViews:self.annotationViews];
	self.pagePicker.delegate = self;
	_navigationPopover = [[UIPopoverController alloc] initWithContentViewController:self.pagePicker];
	self.navigationPopover.popoverContentSize = CGSizeMake(320, 480);
   numberOfPages = CGPDFDocumentGetNumberOfPages(document);
	int i = 0;
	for(i = 0; i < numberOfPages; i++){
		[self.pagePicker loadPdfImageAtIndex:i];
	}
	CGPDFDocumentRelease(document);
	return request;
}

- (void)addDrawViews{
	int page = (int) (self.pdfScrollView.contentOffset.y / heightOfPage);
	int nextPage = page + 1;
	for(UIView *subview in self.pdfScrollView.subviews){
		if([subview class] == [AnnotationView class]){
			if((page == 0 && subview.tag != -1) && subview.tag != nextPage){
				[subview removeFromSuperview];
			}
			else if(page != 0 && subview.tag != page && subview.tag != nextPage){
				[subview removeFromSuperview];
			}
		}
	}
	if(page == 0 && [self.pdfScrollView viewWithTag:-1] == nil){
		[self.pdfScrollView addSubview:[self.annotationViews objectAtIndex:page]];
		[self.pdfScrollView bringSubviewToFront:[self.annotationViews objectAtIndex:page]];
	}
	else if([self.pdfScrollView viewWithTag:page] == nil){
		[self.pdfScrollView addSubview:[self.annotationViews objectAtIndex:page]];
		[self.pdfScrollView bringSubviewToFront:[self.annotationViews objectAtIndex:page]];
	}
	if([self.pdfScrollView viewWithTag:nextPage] == nil && nextPage < [self.annotationViews count]){
		[self.pdfScrollView addSubview:[self.annotationViews objectAtIndex:nextPage]];
		[self.pdfScrollView bringSubviewToFront:[self.annotationViews objectAtIndex:nextPage]];
	}
	for(UIView *subview in self.pdfScrollView.subviews){
		if([subview class] == [NoteTabButton class]){
			[self.pdfScrollView bringSubviewToFront:subview];
		}
	}
}

- (void)saveReading:(NSNumber *)recent{
	if(self.dataReading != nil){
		[DSBezelActivityView removeViewAnimated:YES];
		if([recent boolValue] == NO){
			UIAlertView *alreadySaved = [[[UIAlertView alloc] initWithTitle:@"Already Saved!" message:@"You've already saved this reading." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
			[alreadySaved show];
		}
		return;
	}
	if([recent boolValue] == NO){
		NSArray * readingFetchResults = [self readingFetchResults:NO];
		for(Reading *reading in readingFetchResults){
			if([reading.name isEqualToString:self.pdfName]){
				[DSBezelActivityView removeViewAnimated:YES];
				UIAlertView *alreadySaved = [[[UIAlertView alloc] initWithTitle:@"Already Saved!" message:@"You've already saved this reading." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
				[alreadySaved show];
				return;
			}
		}
	}
	NSString *docroot = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
   NSString *directory = [docroot stringByAppendingPathComponent:@"readings/"];
   NSString *pdfPath = [directory stringByAppendingPathComponent:[self.fileURL lastPathComponent]];
   NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.fileURL]];
   Reading *toSave = [NSEntityDescription insertNewObjectForEntityForName:@"Reading" inManagedObjectContext:[[MarineFetcher sharedInstance] managedObjectContext]];
   toSave.path = pdfPath;
	[toSave setReadingID:[NSNumber numberWithInt:readingID]];
   toSave.thumbnailImage = UIImagePNGRepresentation(self.thumbnail);
   toSave.name = self.pdfName;
	[toSave setIsRecent:recent];
   NSError *e;
   if (![[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&e])
      NSLog(@"%@", [e localizedDescription]);
   if (![pdfData writeToFile:pdfPath atomically:YES])
      NSLog(@"pdf writing failed");
   NSError *saveError;
   [[[MarineFetcher sharedInstance] managedObjectContext] save:&saveError];
	if([recent boolValue] == NO){
		[DSBezelActivityView removeViewAnimated:YES];
		UIAlertView *savedAlert = [[[UIAlertView alloc] initWithTitle:@"Reading Saved!" message:[NSString stringWithFormat:@"'%@' saved.  View your saved readings by showing all classes and clicking the 'Saved Readings' row.", toSave.name] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[savedAlert show];
	}
}

- (void)animateInTutorialView {
   if(![[NSUserDefaults standardUserDefaults] valueForKey:CACHALOT_READING_TUTORIAL_KEY]){
      [self.view addSubview:self.helpView];
      [UIView animateWithDuration:0.4 delay:1.0 options:UIViewAnimationCurveLinear
                       animations:^{
                          self.helpView.alpha = 1.0;
                       }completion:nil];
   }
}

#pragma mark ActionMethods
- (void)dismissTutorial {
   [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES] forKey:CACHALOT_READING_TUTORIAL_KEY];
   [UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationCurveLinear 
                    animations:^{
                       self.helpView.alpha = 0.0;
                    } completion:^(BOOL finished){
                       [self.helpView removeFromSuperview];
                       self.helpView = nil;
                    }];
}

#pragma mark IBActions
- (IBAction)save{
	[DSBezelActivityView newActivityViewForView:self.view withLabel:@"Saving Reading..." width:160];
   dispatch_async(readingQueue, ^{[self saveReading:[NSNumber numberWithBool:NO]];});
}

- (IBAction)note{
	Note *note = [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:[[MarineFetcher sharedInstance] managedObjectContext]];
	note.readingID = [NSNumber numberWithInt:readingID];
	NoteTabButton *noteTabButton = [[[NSBundle mainBundle] loadNibNamed:@"NoteTabButton" owner:nil options:nil] objectAtIndex:0];
	noteTabButton.delegate = self;
	noteTabButton.origin = CGPointMake(NOTE_OFFSET, self.pdfScrollView.contentOffset.y + self.pdfScrollView.height / 2);
	note.y = [NSNumber numberWithInt:noteTabButton.frame.origin.y];
	noteTabButton.noteLabel.text = note.text;
	noteTabButton.note = note;
	[self.pdfScrollView addSubview:noteTabButton];
	[self.pdfScrollView bringSubviewToFront:noteTabButton];
	noteTabButton.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
   [UIView animateWithDuration:0.1 delay:0.0 options:UIViewAnimationOptionCurveLinear 
                    animations:^{
                       noteTabButton.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.1, 1.1);
                    }
                    completion:^(BOOL finished) {
                       [UIView animateWithDuration:0.1 delay:0.0 options:UIViewAnimationOptionCurveLinear
                                        animations:^{
                                           noteTabButton.transform = CGAffineTransformIdentity;
                                        }
                                        completion:nil];
                    }];
}

- (IBAction)notesClicked:(id)sender{
	[self.listOfNotesPopover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)highlightClicked:(id)sender{
	if(self.pdfScrollView.scrollEnabled || sketchingActive || eraseActive){
		[_highlighterButton setBackgroundImage:[UIImage imageNamed:@"highlightActive"] forState:UIControlStateNormal];
		[_sketchingButton setBackgroundImage:[UIImage imageNamed:@"drawInactive"] forState:UIControlStateNormal];
		[_eraserButton setBackgroundImage:[UIImage imageNamed:@"eraseInactive"] forState:UIControlStateNormal];
		highlighterActive = YES;
		sketchingActive = NO;
		eraseActive = NO;
		self.pdfScrollView.scrollEnabled = NO;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldDraw = YES;
			annotationView.highlighting = YES;
			annotationView.shouldErase = NO;
		}
	}
	else{
		[_highlighterButton setBackgroundImage:[UIImage imageNamed:@"highlightInactive"] forState:UIControlStateNormal];
		highlighterActive = NO;
		self.pdfScrollView.scrollEnabled = YES;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldDraw = NO;
			annotationView.highlighting = NO;
			annotationView.shouldErase = NO;
		}
	}
}

- (IBAction)sketchClicked:(id)sender{
	if(self.pdfScrollView.scrollEnabled || highlighterActive || eraseActive){
		[_sketchingButton setBackgroundImage:[UIImage imageNamed:@"drawActive"] forState:UIControlStateNormal];
		[_highlighterButton setBackgroundImage:[UIImage imageNamed:@"highlightInactive"] forState:UIControlStateNormal];
		[_eraserButton setBackgroundImage:[UIImage imageNamed:@"eraseInactive"] forState:UIControlStateNormal];
		sketchingActive = YES;
		highlighterActive = NO;
		eraseActive = NO;
		self.pdfScrollView.scrollEnabled = NO;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldDraw = YES;
			annotationView.highlighting = NO;
			annotationView.shouldErase = NO;
		}
	}
	else{
		[_sketchingButton setBackgroundImage:[UIImage imageNamed:@"drawInactive"] forState:UIControlStateNormal];
		sketchingActive = NO;
		self.pdfScrollView.scrollEnabled = YES;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldDraw = NO;
			annotationView.highlighting = NO;
			annotationView.shouldErase = NO;
		}
	}
}

- (IBAction)eraseClicked:(id)sender{
	if(self.pdfScrollView.scrollEnabled || highlighterActive || sketchingActive){
		[_sketchingButton setBackgroundImage:[UIImage imageNamed:@"drawInactive"] forState:UIControlStateNormal];
		[_highlighterButton setBackgroundImage:[UIImage imageNamed:@"highlightInactive"] forState:UIControlStateNormal];
		[_eraserButton setBackgroundImage:[UIImage imageNamed:@"eraseActive"] forState:UIControlStateNormal];
		eraseActive = YES;
		highlighterActive = NO;
		sketchingActive = NO;
		self.pdfScrollView.scrollEnabled = NO;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldErase = YES;
			annotationView.shouldDraw = NO;
			annotationView.highlighting = NO;
		}
	}
	else{
		[_eraserButton setBackgroundImage:[UIImage imageNamed:@"eraseInactive"] forState:UIControlStateNormal];
		eraseActive = NO;
		self.pdfScrollView.scrollEnabled = YES;
		for(AnnotationView *annotationView in self.annotationViews){
			annotationView.shouldErase = NO;
			annotationView.shouldDraw = NO;
			annotationView.highlighting = NO;
		}
	}
}

- (IBAction)colorClicked:(id)sender{
	[self.colorPopover presentPopoverFromRect:[sender frame] inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)widthClicked:(id)sender{
	[self.penWidthPopover presentPopoverFromRect:[sender frame] inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)clear{
	UIAlertView *clearView = [[[UIAlertView alloc] initWithTitle:@"Clear Annotations?" message:@"Are you sure you want to remove all your annotations from this reading?  Notes will not be deleted." delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil] autorelease];
	[clearView show];
}

- (IBAction)navigate:(id)sender{
	[self.navigationPopover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

#pragma mark UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
	[self setupAnnotationViews];
	[self setupNotes];
	[self setupPopovers];
	[self cacheReading];
	[self setupHelpView];
   [self animateInTutorialView];
   
	[DSBezelActivityView removeViewAnimated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	[self addDrawViews];
}

#pragma mark PDFPagePickerGridViewControllerDelegate
- (void)pageSelected:(int)selectedPage{
	[self.pdfScrollView setContentOffset:CGPointMake(0, selectedPage * heightOfPage) animated:NO];
	[self addDrawViews];
}

#pragma mark NoteTabButtonDelegate
- (void)showNote:(NSString *)text button:(NoteTabButton *)tabButton{
	NoteViewController *noteVC = [[NoteViewController alloc] initWithNibName:nil bundle:[NSBundle mainBundle] text:text];
	noteVC.delegate = tabButton;
	if(_notePopover == nil){
		_notePopover = [[UIPopoverController alloc] initWithContentViewController:noteVC];
	}
	else {
		self.notePopover.contentViewController = noteVC;
	}
	self.notePopover.popoverContentSize = CGSizeMake(320, NOTE_CONTENT_HEIGHT);
	CGRect rect = tabButton.frame;
	[self.notePopover presentPopoverFromRect:rect inView:self.pdfScrollView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
	[noteVC release];
	
}

- (void)noteDeleted:(Note *)note{
	[[[MarineFetcher sharedInstance] managedObjectContext] deleteObject:note];
	[self.notePopover dismissPopoverAnimated:YES];
}

- (void)noteEmailed:(NSString *)text{
	[self.notePopover dismissPopoverAnimated:YES];
	MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
	mailVC.mailComposeDelegate = self;
	[mailVC setSubject:[NSString stringWithFormat:@"%@ Notes", self.pdfName]];
	NSString *notes = [NSString stringWithFormat:@"<strong>Here is a note for %@:</strong><br /><br />%@", self.pdfName, text];
   notes = [notes stringByAppendingString:CACHALOT_SINGLE_NOTE_EMAIL_TEXT];
	[mailVC setMessageBody:notes isHTML:YES];
	[self presentModalViewController:mailVC animated:YES];
	[mailVC release];
}

#pragma mark AnnotationViewDelegate
- (void)saveDrawing:(NSMutableArray *)touchPoints atPage:(int)page{
	[self.annotationTouchPoints replaceObjectAtIndex:page withObject:touchPoints];
	NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
	NSString *fileDrawing = [NSString stringWithFormat:@"reading%d", readingID];
	path = [path stringByAppendingPathComponent:fileDrawing];
   [NSKeyedArchiver archiveRootObject:self.annotationTouchPoints toFile:path];
   [self.pagePicker.gridView reloadData];
}

#pragma mark NotesTableViewControllerDelegate
- (void)noteClicked:(Note *)note{
	self.pdfScrollView.contentOffset = CGPointMake(self.pdfScrollView.contentOffset.x, [note.y intValue]);
	[self addDrawViews];
	[self.listOfNotesPopover dismissPopoverAnimated:YES];
}

- (void)allNotesEmailed:(NSString *)notesText{
	[self.listOfNotesPopover dismissPopoverAnimated:YES];
	MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
	mailVC.mailComposeDelegate = self;
	[mailVC setSubject:[NSString stringWithFormat:@"%@ Notes", self.pdfName]];
	NSString *notes = [NSString stringWithFormat:@"<strong>Here are all the notes for %@:</strong><br /><br />%@", self.pdfName, notesText];
   notes = [notes stringByAppendingString:CACHALOT_MULTIPLE_NOTE_EMAIL_TEXT];
	[mailVC setMessageBody:notes isHTML:YES];
	[self presentModalViewController:mailVC animated:YES];
	[mailVC release];
}

#pragma mark MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	if(buttonIndex != 0){
		for(AnnotationView *annotationView in self.annotationViews){
			[annotationView clear];
		}
	}
}

@end
